package com.example.erp.service.impl;

import cn.hutool.core.util.StrUtil;
import com.example.erp.config.CommonConfig;
import com.example.erp.service.FileService;
import com.example.erp.utils.DataFormatUtils;
import com.example.erp.utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Map;

@Service
public class FileServiceA implements FileService {
    // 使用常量和配置属性
    @Value("${directoryConfig.picPath}")
    private String picPath;

    @Value("${directoryConfig.filePath}")
    private String filePath;

    @Value("${directoryConfig.staticPicUrl}")
    private String staticPicUrl;

    @Value("${directoryConfig.staticFileUrl}")
    private String staticFileUrl;

    /**
     * 上传图片
     */
    @Override
    public Result uploadPic(MultipartFile file,String url) {    // 参数校验
        if (file == null || file.isEmpty()) {
            return Result.error(CommonConfig.uploadMsg.FILENULL.getDescription());
        }
        /**
         * 获取文件名
         * */
        String originalFilename = file.getOriginalFilename();
        if (StrUtil.isEmpty(originalFilename)) {
            return Result.error(CommonConfig.uploadMsg.FILENAMENULL.getDescription());
        }
        String fileExtension = DataFormatUtils.getFileExtension(originalFilename).toLowerCase();
        System.out.println(file.getName());
        System.out.println(file.getOriginalFilename());
        System.out.println(fileExtension);
        if (!DataFormatUtils.isAllowedFileType(fileExtension)) {
            throw new IllegalArgumentException("不支持的文件类型");
        }
        String basePath = picPath+url;
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String newFile = System.currentTimeMillis() +"."+fileExtension;
        File destFile = new File(basePath + newFile);
        try{
            file.transferTo(destFile);
            return Result.upload(Map.of(
                    "fileName", newFile,
                    "fileUrl", staticPicUrl+url+newFile
            ));
        }catch(Exception e){
            return Result.error(CommonConfig.uploadMsg.UPLOADERROR.getDescription());
        }
    }
}
